<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>Admin</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="30">
        <el-col :span="7">
          <el-input placeholder="请输入内容" @keyup.enter.native="serchUser(serchU)" v-model="serchU" clearable @clear="fetch()">
            <el-button slot="append" icon="el-icon-search" @click="serchUser(serchU)"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true" v-if="this.admin === 'admin'">添加管理员</el-button>
        </el-col>
      </el-row>
      <!-- 添加用户对话框弹窗 -->
      <el-dialog title="新增管理员信息" :visible.sync="addDialogVisible" width="50%" @close="addCloseDia">
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
          <el-form-item label="用户名" prop="name">
            <el-input v-model="addForm.name"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="tel">
            <el-input v-model="addForm.tel"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog title="修改账号信息" :visible.sync="editDialogVisible" width="50%" @close="editCloseDia">
        <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="70px">
          <el-form-item label="用户名" prop="name">
            <el-input v-model="editForm.name" disabled></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="tel">
            <el-input v-model="editForm.tel"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUserInfo">确 定</el-button>
        </span>
      </el-dialog>
      <el-table :data="users" border stripe>
        <el-table-column label="#" type="index" ></el-table-column>
        <el-table-column label="用户名" prop="name"></el-table-column>
        <el-table-column label="密码" prop="password"></el-table-column>
        <el-table-column label="电话" prop="tel"></el-table-column>
        <el-table-column label="操作" align="right" v-if="this.admin === 'admin'">
          <template slot-scope="scope">
            <el-tooltip content="修改信息" placement="top" effect="light" :enterable="false">
              <el-button
                size="mini"
                icon="el-icon-edit"
                @click="handleEdit(scope.row.ad_id)"
                type="primary"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除信息" placement="top" effect="light" :enterable="false">
              <el-button
                size="mini"
                icon="el-icon-delete"
                @click="handleDelete(scope.row.ad_id)"
                type="danger"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.currentPage"
      :page-sizes="[5, 10, 15, 30]"
      :page-size="queryInfo.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total=queryInfo.total>
    </el-pagination>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    var checkTel = (rule, value, callback) => {
      const regTel = /^((13[0-9])|(17[0-1,6-8])|(15[^4,\\D])|(18[0-9]))\d{8}$/
      if (regTel.test(value)) {
        return callback()
      }
      callback(new Error('手机号格式不正确'))
    }
    return {
      queryInfo: {
        currentPage: 1,
        // 当前每页显示多少条数据
        pageSize: 5,
        total: 0
      },
      users: [],
      serchU: '',
      // 添加用户对话框的显示与隐藏
      addDialogVisible: false,
      editDialogVisible: false,
      addForm: {
        name: '',
        password: '',
        tel: ''
      },
      admin: '',
      editForm: [],
      addFormRules: {
        name: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        tel: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkTel, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async fetch() {
      const { data: res } = await this.$http.get('/admin', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败！')
      }
      this.users = res.usersxx
      // console.log(this.users)
      this.queryInfo = res.pagination
    },
    async serchUser(val) {
      const { data: res } = await this.$http.get(`admin?name=${val}`)
      this.users = res.usersxx
      this.queryInfo = res.pagination
    },
    handleSizeChange(val) {
      this.queryInfo.pageSize = val
      this.fetch()
    },
    async handleCurrentChange(val) {
      this.queryInfo.currentPage = val
      this.fetch()
    },
    async handleEdit(id) {
      const { data: res } = await this.$http.get(`/admin${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户信息失败')
      }
      this.editForm = res.usersedit
      this.editDialogVisible = true
    },
    editUserInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('/admin' + this.editForm.ad_id, this.editForm)
        if (res.meta.status !== 200) {
          return this.$message.error('更新用户信息失败')
        }
        this.$message.success('更新用户信息成功')
        // 隐藏添加用户对话框并刷新用户列表
        this.editDialogVisible = false
        this.fetch()
      })
    },
    handleDelete(id) {
      this.$confirm('此操作将永久删除用户信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$http.delete(`admin${id}`).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.fetch()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('/admin', this.addForm)
        if (res.status === 403) {
          this.$message({
            type: 'error',
            message: '登录已失效，请重新登录！'
          })
          this.$router.push('/login')
          return false
        }
        if (res.meta.status !== 201) {
          return this.$message.error('添加管理员失败')
        }
        this.$message.success('添加管理员成功')
        // 隐藏添加用户对话框并刷新用户列表
        this.addDialogVisible = false
        this.fetch()
      })
    },
    addCloseDia() {
      this.$refs.addFormRef.resetFields()
    },
    editCloseDia() {
      this.$refs.editFormRef.resetFields()
    }
  },
  created() {
    this.fetch()
    this.admin = sessionStorage.getItem('name')
  }
}
</script>

<style lang="less" scoped>
</style>
